<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form id="guide_form" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
            class="demo-ruleForm">
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="queryWeighingList">
                    <el-option v-if="Number(data.facilityId) == Number(item.facilityId) && item.status != 'COMPLETED'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-form-item label="使用称重记录">
                <el-switch v-model="isUseWeightList" @change="handChangeWeightList" active-color="#13ce66"
                    inactive-color="#ff4949" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否">
                </el-switch>
            </el-form-item>
            <template v-if="isUseWeightList">
                <el-form-item label="称重记录">
                    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" height="154" border
                        style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="plantVarietyName" label="品种"></el-table-column>
                        <el-table-column prop="specificationName" label="规格"></el-table-column>
                        <el-table-column prop="weight" label="重量(斤)"></el-table-column>
                        <el-table-column prop="num" label="粒数(粒)"></el-table-column>
                    </el-table>
                </el-form-item>
            </template>
            <template v-if="!isUseWeightList">
                <!-- <el-form-item label="选择规格" prop="item12">
                    <el-select v-model="ruleForm.item12" class="w100p" placeholder="请选择规格">
                        <el-option label="1-2斤" value="1-2斤"></el-option>
                        <el-option label="2-3斤" value="2-3斤"></el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="入鱼数量(粒)" prop="inputPondDetailList">
                    <el-input v-model="ruleForm.inputPondDetailList" class="w100p" placeholder="请选择称重数量"></el-input>
                </el-form-item>
                <el-form-item label="入鱼重量(斤)" prop="item7">
                    <el-input v-model="ruleForm.item7" class="w100p" placeholder="请选择称重重量"></el-input>
                </el-form-item> -->
                <el-row v-for="item, index in ruleForm.inputPondDetailList" :key="index">
                    <el-col :span="10">
                        <el-form-item :label="index == 0 ? '养殖品种' : ''"
                            :prop="`inputPondDetailList[${index}][plantVarietyId]`" :rules="rules.plantVarietyId">
                            <el-select clearable v-model="item.plantVarietyId" class="w100p" placeholder="请选择养殖品种"
                                @change="(e) => {
                                    getDateName(varietyList, e, index, 'plantVarietyId', 'plantVarietyName');
                                    getSpecification(e, index);
                                }">
                                <el-option v-for="v, index in varietyList" :key="index" :label="v.plantVarietyName"
                                    :value="v.plantVarietyId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="index == 0 ? '规格' : ''"
                            :prop="`inputPondDetailList[${index}][specificationId]`" :rules="rules.specificationId">
                            <el-select clearable v-model="item.specificationId" class="w100p" placeholder="请选择养殖品种"
                                @change="(e) => { getDateName(specificationList, e, index, 'specificationId', 'specificationName') }">
                                <el-option v-if="s.plantVarietyId == item.plantVarietyId"
                                    v-for="s, index in specificationList" :key="index" :label="s.specificationName"
                                    :value="s.specificationId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="index == 0 ? '称重粒数' : ''" :prop="`inputPondDetailList[${index}][num]`"
                            :rules="rules.num">
                            <el-input type="number" v-model="item.num" placeholder="请输入称重粒数">
                                <template slot="append">粒</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="index == 0 ? '称重总重' : ''" :prop="`inputPondDetailList[${index}][weight]`"
                            :rules="rules.weight">
                            <el-input type="number" v-model="item.weight" placeholder="请输入称重总重"><template
                                    slot="append">斤</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                        <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                    </el-col>
                </el-row>
            </template>
            <el-form-item label="操作人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="投塘日期" prop="inputDate">
                <el-date-picker v-model="ruleForm.inputDate" value-format="yyyy-MM-dd" align="right" type="date"
                    placeholder="选择日期" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm" id="guide_form_add">确 定</el-button>
        </span>
        <div class="guideBox" v-if="isGuide">
            <div class="routerInfo" :style="guideStyle"
                v-if="isGuide && guideInfo.index > 0 && guideInfo.procedure.length">
                <div class="guideText">{{ guideIndex + 1 }}. {{ guideInfo.procedure && guideInfo.procedure.length >
                    0 ?
                    guideInfo.procedure[guideIndex]
                    : '' }}</div>
                <div class="guideNext" @click="guideNext" v-if="guideInfo.procedure.length > (guideIndex + 1)">下一步
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import specificationManagement from '@/api/basicInformation/specificationManagement.js';
import varietyManagement from '@/api/basicInformation/varietyManagement';
import batch from '@/api/batch/batchManagement';
import weighingManagement from '@/api/pondManagment/weighingManagement.js';

import pondInformationManagement from '@/api/pondManagment/pondInformationManagement.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0 && value % 1 == 0) {
                callback()
            } else {
                callback(new Error('请输入大于0整数！'))
            }
        }
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            guideIndex: 0,
            guideStyle: {},
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                specificationId: [
                    { required: true, message: '请选择规格', trigger: 'change' }
                ],
                inputPondDetailList: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                inputDate: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择鱼种', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
            },
            inputPondDetailList: [],
            isUseWeightList: 0,
            tableData: [],
            batchList: [],
            specificationList: [],
            varietyList: [],
            fishPondScope: 0,
            unitName: '',
            pondRatio: 0
        }
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
        guideInfo() {
            return this.$store.state.user.guideInfo;
        },
        isGuide() {
            return this.$store.state.user.isGuide || ''
        },
    },
    watch: {
        guideInfo: {
            handler(v) {
                this.setGuide(v)
                console.log(v)
            },
            deep: true
        },
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() {
        this.getselectlist();
    },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                if (this.ruleForm.inputPondDetailList && Array.isArray(this.ruleForm.inputPondDetailList)) {
                    this.$set(this.ruleForm.inputPondDetailList, 0, {
                        weight: null, num: null, specificationId: null, plantVarietyId: null, plantVarietyName: null
                    })
                } else {
                    this.$set(this.ruleForm, 'inputPondDetailList', [{
                        weight: null, num: null, specificationId: null, plantVarietyId: null, plantVarietyName: null
                    }])
                }
                this.addEditApi = pondInformationManagement.add
                this.addEditName = '添加';
                setTimeout(() => {
                    this.setGuide(this.guideInfo || {})
                }, 500);
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                }
                this.addEditApi = pondInformationManagement.edit
                this.addEditName = '编辑'
            }
            this.getFacility(this.data.facilityId);
        },
        guideNext() {
            let { index, procedure } = this.guideInfo;
            this.$store.dispatch("user/getGuideInfo", {
                procedure: procedure,
                index: index + 1
            });
        },
        setGuide(v) {
            if (!this.isGuide) return;
            let { index } = v;
            this.guideIndex = index;
            let btn = document.getElementById('guide_form_add');
            let formDom = document.getElementById('guide_form');
            console.log(formDom, btn, index)
            this.resetGuide(formDom);
            this.resetGuide(btn);
            if (index == 2) {
                formDom && (formDom.className += " guide-name");
                this.guideStyle = {
                    top: '12%',
                    right: '29%',
                    wayFlag: 'right'
                }
            } else if (index == 3) {
                btn && (btn.className += " guide-name");
                this.guideStyle = {
                    top: '50%',
                    right: '30%',
                    wayFlag: 'right'
                }
            } else {
                this.resetForm(); this.cancel()
            }
        },
        resetGuide(node) {
            node&&(node.className = node.className.replace("guide-name", ""))
        },
        getDateName(list, e, index, idKey, key) {
            console.log(e, index)
            let name = this.$public.foundObject(list, idKey, e)[key] || '';
            this.$set(this.ruleForm.inputPondDetailList[index], key, name)
        },
        handChangeWeightList(v) {
            if (v == 1 && !this.ruleForm.batchId) {
                this.$message.warning('请先选择批次！')
            } else if (this.isUseWeightList == 1 && this.tableData.length == 0) {
                this.$message.warning('未查询到该批次的称重记录，请先称重后选择称重记录，或再本窗口手动添加称重！')
            }
        },
        getSpecification(id, index) {
            this.ruleForm.inputPondDetailList[index].specificationId = null
            this.ruleForm.inputPondDetailList[index].specificationName = null
        },
        //获取鱼塘面积
        getFacility(facilityId) {
            let result = this.facilityList.find(obj => obj.facilityId == facilityId) || {};
            this.fishPondScope = result && result.scope ? result.scope : 0;
            if (result.unitName !== '亩' || result.unitName !== '平方米') {
                this.unitName = '亩'
            } else {
                this.unitName = result.unitName
            }
        },
        async queryWeighingList(batchId) {
            //获取鱼塘占比
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.pondRatio = result.pondRatio
            console.log(result)
            let { data: tableList } = await weighingManagement.queryByCondition({ batchId });
            this.tableData = tableList || [];
            this.tableData = this.tableData.filter(item => { return item.status == false });
            if (this.isUseWeightList == 1 && this.tableData.length == 0) {
                this.$message.warning('未查询到该批次的称重记录，请先称重后选择称重记录，或再本窗口手动添加称重！')
            };
        },
        useWeightRecord() {
            let list = [];
            // 如果选择称重记录并且有记录
            if (this.isUseWeightList == 1 && this.inputPondDetailList.length > 0) {
                this.inputPondDetailList.forEach(item => {
                    list.push(item.weightRecordId)
                })
                weighingManagement.useWeightRecord(list)
            }
        },
        densityRemind(list) {
            let PromiseList = []
            list.forEach(item => {
                PromiseList.push(pondInformationManagement.densityRemind(item))
            })
            Promise.all(PromiseList).then(resList => {
                let warningList = resList.filter(item => { return item.code !== 1 });
                if (warningList.length > 0) {
                    this.$confirm('该设施的该品种密度已超出配置, 是否继续投塘?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        this.submitInfo();
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                } else {
                    this.submitInfo()
                }
            }).catch(err => {
                console.log(err)
            })
        },
        // 获取下拉数据
        async getselectlist() {
            // 获取批次列表 
            let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' });
            this.batchList = batchList;
            console.log('批次------------------------', this.batchList)
            //规格；
            let { data: specificationList } = await specificationManagement.queryByCondition({});
            this.specificationList = specificationList;
            //获取品种；
            let { data: varietyList } = await varietyManagement.queryByCondition({});
            this.varietyList = varietyList || [];
        },
        //选中table项
        handleSelectionChange(val) {
            console.log(val)
            this.inputPondDetailList = val;
        },
        addMaterial() {
            let length = this.ruleForm.inputPondDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.inputPondDetailList, length, {
                    weight: null, num: null, specificationId: null, plantVarietyId: null, plantVarietyName: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.inputPondDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'inputPondDetailList', list)
        },
        dataProcessing() {
            // 查找与当前表单中的 staffId 匹配的人员，并设置其姓名到表单的 staffName 字段  
            const personMatch = this.person.find(obj => obj.personNo === this.ruleForm.staffId);
            if (personMatch) {
                this.$set(this.ruleForm, 'staffName', personMatch.person.name || "");
            } else {
                this.$set(this.ruleForm, 'staffName', "");
            }

            // 查找与当前表单中的 batchId 匹配的批次，并设置其名称到表单的 batchName 字段  
            const batchMatch = this.batchList.find(obj => obj.batchId === this.ruleForm.batchId);
            if (batchMatch) {
                this.$set(this.ruleForm, 'batchName', batchMatch.batchName || "");
            } else {
                this.$set(this.ruleForm, 'batchName', "");
            }
            this.$set(this.ruleForm, 'facilityId', this.data.facilityId);
            this.$set(this.ruleForm, 'facilityName', this.data.facilityName);

            if (this.isUseWeightList == 1 && this.inputPondDetailList.length > 0) {
                this.$set(this.ruleForm, 'inputPondDetailList', this.inputPondDetailList);
            }
        },
        //提交表单
        submitForm() {
            if (this.isUseWeightList == 1 && this.inputPondDetailList == 0) {
                this.$message.warning('请先选择称重记录！');
                return
            }
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.dataProcessing();
                    let inputPondDetailList = this.ruleForm.inputPondDetailList.map(item => {
                        return {
                            ...item,
                            ...this.ruleForm,
                            scope: (this.fishPondScope / this.pondRatio).toFixed(2),
                            unitName: this.unitName
                        }
                    })
                    this.densityRemind(inputPondDetailList);

                } else {
                    return false;
                }
            })
        },
        submitInfo() {
            let inputPondDetailList = this.ruleForm.inputPondDetailList.map(item => {
                return {
                    ...item,
                    scope: (this.fishPondScope / this.pondRatio).toFixed(2),
                    unitName: this.unitName
                }
            })
            this.addEditApi({
                ...this.ruleForm,
                scope: (this.fishPondScope / this.pondRatio).toFixed(2),
                unitName: this.unitName,
                inputPondDetailList: inputPondDetailList
            }).then(res => {
                this.useWeightRecord();
                this.cancel();
                this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || res.code == 1 ? '添加成功' : '添加失败')
            }).catch(err => {
                console.log(err)
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.inputPondDetailList = [];
            this.isUseWeightList = 0;
            this.tableData = [];
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}

.guideBox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #00000030;
    z-index: 10;
}

.routerInfo {
    max-width: 400px;
    min-width: 300px;
    padding: 10px;
    background-color: #FF9243;
    color: #ffffff;
    position: fixed;
    z-index: 9999;

    .guideText {
        width: 100%;
        text-align: left;
        line-height: 26px;
    }

    .guideNext {
        width: 100px;
        margin-top: 15px;
        background-color: #e4a579;
        border: 1px solid #c65504;
        border-radius: 4px;
        text-align: center;
        line-height: 28px;
        cursor: pointer;

        &:hover {
            background-color: #d88244;
        }
    }
}

::v-deep {

    .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
        z-index: 0;
    }

    .el-checkbox__inner {
        z-index: 0;
    }
}

#guide_form {
    background-color: #ffffff;
}
</style>